<?php
declare (strict_types = 1);

namespace app\api\controller\v1;

use app\api\model\v1\AdminLog;
use app\api\model\v1\Admins;
use app\api\model\v1\AuthRule;
use app\api\validate\v1\AdminValidate;
use app\BaseController;
use Jenssegers\Agent\Agent;
use think\exception\ValidateException;
use think\Request;

class Admin extends BaseController
{

    /**
     * @User: 刘海龙
     * @Date: 2021/9/23
     * @Time: 17:57
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * 用户列表
     */
    public function adminList()
    {
        //获取每页显示的条数
        $limit = $this->request->param('limit');
        $map = [];
        if ($this->request->has('username') && !empty($this->request->param('username'))) {
            $map[] = ['username', 'like', '%' . $this->request->param('username') . '%'];
        }
        if ($this->request->has('mobile') && !empty($this->request->param('mobile'))) {
            $map[] = ['mobile', 'like', '%' . $this->request->param('mobile') . '%'];
        }
        $data = Admins::with(['roles'])->where($map)->paginate($limit)->each(function ($item, $key) {
            $pinjie = "";
            foreach ($item['roles'] as $k => $v) {
                $pinjie .= $v['name'] . ',';
            }
            $item['role_name'] = rtrim($pinjie, ',');

            return $item;

        });
        return $this->response($data);
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/9/23
     * @Time: 18:05
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 更新
     */
    public function adminUpdateShow()
    {
        $id = $this->request->param('id');
        $user = Admins::find($id);
        if (is_null($user)) {
            return $this->response(404, '此用户不存在');
        }
        // 检查用户权限
        $role_ids = array_column($user->roles()->select()->toArray(),
            'rules');//获取该用户所属角色rules
        if (in_array('*', $role_ids)) {
            $data =
                AuthRule::field('id,name')->where('is_open', AuthRule::OPEN_ONE)
                    ->select()
                    ->toArray();
        } else {
            $data = AuthRule::field('id,name')
                ->where('id', 'in', implode(',', $role_ids))
                ->where('is_open', AuthRule::OPEN_ONE)
                ->select()->toArray();
        }
        $url = [];
        foreach ($data as $key => $v) {
            $url[] = $v['name'];
        }
        $user['url'] = implode(',', $url);
        return $this->response($user->toArray());
    }
    /**
     * @User: 刘海龙
     * @Date: 2021/9/23
     * @Time: 18:04
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 新增或编辑
     */
    public function adminSave()
    {

        $id = $this->request->param('id', 0);

        try {
            $validator = $this->validate($this->request->param(),
                AdminValidate::rules($id),
                AdminValidate::msg());
            if ($validator) {
                $data = $this->request->except(['password_confirm']);
                if (empty($data['enter_unit_id'])) {
                    $data['enter_unit_id'] = 0;
                }
                if (intval($id) === 0) {
                    $data['password'] = password_hash(!empty($data['password']) ? $data['password'] : '111111', PASSWORD_DEFAULT);
                    $data['create_id'] = $this->request->uid ?? 0;
                    Admins::create($data);
                } else {
                    if (empty($data['password'])) {
                        unset($data['password']);
                    } else {
                        $data['password'] = password_hash($data['password'], PASSWORD_DEFAULT);
                    }
                    $user = Admins::find($id);
                    $user->update($data);
                }
                AdminLog::record(intval($id) === 0 ? '新增用户' : '编辑用户', $this->request->param(), $this->request->uid, $this->request->username);
                //添加用户角色中间表信息
                //GroupUserPivot::roleUserSave($user,$this->request->param('role_id'));
                return $this->response();
            }
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return $this->response(403, $e->getError());
        }
    }
    /**
     * @param $id
     * @User: 刘海龙
     * @Date: 2021/9/23
     * @Time: 18:03
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 删除用户
     */
    public function adminDelete($id)
    {
        $ids = explode(',', $id);
        foreach ($ids as $id) {
            if (intval($id) === 1) {
                return $this->response(403, '超级管理员,不能删除');
            }
            $user = Admins::find($id);
            if (is_null($user)) {
                return $this->response(404, '此用户不存在');
            }
            //->force()
            $user->delete();
            AdminLog::record('删除用户', $this->request->param(), $this->request->uid, $this->request->username);
        }
        return $this->response();
    }


    public function getLog(){
        $agent = new Agent();
        $headers = $agent->setUserAgent('Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36');
        $agent->setHttpHeaders($headers);
        halt($agent->browser());
    }

}
